package com.yulinlin.lang.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;


public class JsonUtil {

    private static ObjectMapper mapper;

    static {
        mapper=new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    }

    private static ObjectMapper getMapper(){
        return mapper;
    }


    public static String toJson(Object obj)  {

        ObjectMapper mapper =getMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("对象转换异常:"+obj);
        }
    }


    public static <T> T parseJson(String json,Class<T> cla,Class<?>... clazz) {

        try {
            if(clazz.length == 0){
                return mapper.readValue(json,cla);
            }else{
                ObjectMapper mapper =getMapper();
                JavaType javaType =  mapper.getTypeFactory()
                        .constructParametricType(cla, clazz);
                return mapper.readValue(json,javaType);
            }


        } catch (Exception e) {
          throw  new RuntimeException(e);
        }
    }


    private static <T> T parseParameterizedType(String json,ParameterizedType parameterizedType) {
        try {
            ObjectMapper objectMapper =getMapper();
            JavaType javaType=objectMapper.getTypeFactory().constructType(parameterizedType);
            return  objectMapper.readValue(json, javaType);
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }

    public static <T> T parseByField(String json,Field f) {
        ParameterizedType type = (ParameterizedType)  f.getGenericType();
        return  parseParameterizedType(json,type);
    }


    public static <T> T parseByClass(String json,Class f) {
        ParameterizedType type = (ParameterizedType)  f.getGenericSuperclass();
        return  parseParameterizedType(json,type);
    }





}

